package com.hww.mq.producer;

import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: youdao.hww
 * @Date: 5/18/24
 * @Desc:
 */
@Component
public class MQTransactionMessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public void sendTransactionalMessage(String topic, String tag, String key, String messageBody, Object arg) {


        TransactionMQProducer transactionMQProducer = new TransactionMQProducer();



        Message<String> msg = MessageBuilder.withPayload(messageBody)
                .setHeader(RocketMQHeaders.KEYS, "key").build();
        // 发送事务消息，arg为事务上下文，用于在executeLocalTransaction中识别事务
        rocketMQTemplate.sendMessageInTransaction(topic + ":" + tag, msg, arg);
    }
}
